"""
MySQL数据库配置文件
"""
import os
from urllib.parse import quote_plus

class MySQLConfig:
    """MySQL数据库配置类"""
    
    # 基础配置
    MYSQL_HOST = os.environ.get('MYSQL_HOST', 'localhost')
    MYSQL_PORT = int(os.environ.get('MYSQL_PORT', 3306))
    MYSQL_USER = os.environ.get('MYSQL_USER', 'root')
    MYSQL_PASSWORD = os.environ.get('MYSQL_PASSWORD', 'password')
    MYSQL_DATABASE = os.environ.get('MYSQL_DATABASE', 'scheduled_task_platform')
    MYSQL_CHARSET = os.environ.get('MYSQL_CHARSET', 'utf8mb4')
    
    # 连接池配置
    MYSQL_POOL_SIZE = int(os.environ.get('MYSQL_POOL_SIZE', 10))
    MYSQL_POOL_TIMEOUT = int(os.environ.get('MYSQL_POOL_TIMEOUT', 20))
    MYSQL_POOL_RECYCLE = int(os.environ.get('MYSQL_POOL_RECYCLE', 3600))
    MYSQL_MAX_OVERFLOW = int(os.environ.get('MYSQL_MAX_OVERFLOW', 20))
    
    @classmethod
    def get_database_uri(cls):
        """获取MySQL数据库连接URI"""
        # URL编码密码以处理特殊字符
        encoded_password = quote_plus(cls.MYSQL_PASSWORD)
        
        uri = (f"mysql+pymysql://{cls.MYSQL_USER}:{encoded_password}@"
               f"{cls.MYSQL_HOST}:{cls.MYSQL_PORT}/{cls.MYSQL_DATABASE}"
               f"?charset={cls.MYSQL_CHARSET}")
        
        return uri
    
    @classmethod
    def get_engine_options(cls):
        """获取SQLAlchemy引擎选项"""
        return {
            'pool_size': cls.MYSQL_POOL_SIZE,
            'pool_timeout': cls.MYSQL_POOL_TIMEOUT,
            'pool_recycle': cls.MYSQL_POOL_RECYCLE,
            'max_overflow': cls.MYSQL_MAX_OVERFLOW,
            'pool_pre_ping': True,  # 连接前检查连接是否有效
            'echo': os.environ.get('MYSQL_ECHO', 'False').lower() == 'true'
        }
    
    @classmethod
    def validate_config(cls):
        """验证MySQL配置"""
        required_fields = ['MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE']
        missing_fields = []
        
        for field in required_fields:
            if not getattr(cls, field):
                missing_fields.append(field)
        
        if missing_fields:
            raise ValueError(f"MySQL配置缺少必要字段: {', '.join(missing_fields)}")
        
        return True

# 默认配置实例
mysql_config = MySQLConfig()